import pymysql


class AsyncContextManger:
    def __init__(self):
        var = self.cursor
        var = self.db

    async def inset_many(self, sql, values):
        global res
        try:
            # 执行sql语句
            res = self.cursor.executemany(sql, values)
            # 提交到数据库执行
            self.db.commit()
        except Exception as err:
            # 如果发生错误则回滚
            print(err)
            self.db.rollback()
        return res

    async def __aenter__(self):
        """
        进入方法时执行这个函数
        :return:
        """
        self.db = pymysql.connect("localhost", "root", "root", "fastadmin")
        # 使用cursor()方法获取操作游标
        self.cursor = self.db.cursor()

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        self.cursor.close()
        self.db.close()

async with AsyncContextManger() as f:
    await f.inset_many()